<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="数据库名称" prop="dbName">
        <el-input
          v-model="queryParams.dbName"
          placeholder="请输入数据库名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据库类型" prop="dbType">
        <el-select v-model="queryParams.dbType" placeholder="请选择数据库类型" clearable>
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:dbconfig:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:dbconfig:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:dbconfig:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:dbconfig:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dbConfigList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="数据库ID" align="center" prop="dbId" />
      <el-table-column label="数据库名称" align="center" prop="dbName" :show-overflow-tooltip="true" />
      <el-table-column label="数据库类型" align="center" prop="dbType" :show-overflow-tooltip="true" />
      <el-table-column label="连接地址" align="center" prop="dbUrl" :show-overflow-tooltip="true" />
      <el-table-column label="驱动类" align="center" prop="dbDriver" :show-overflow-tooltip="true" />
      <el-table-column label="用户名" align="center" prop="dbUsername" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dbconfig:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dbconfig:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-connection"
            @click="handleTest(scope.row)"
            v-hasPermi="['system:dbconfig:test']"
          >测试</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="数据库名称" prop="dbName">
          <el-input v-model="form.dbName" placeholder="请输入数据库名称" @input="handleDbNameChange" />
        </el-form-item>
        <el-form-item label="服务器" prop="serverId">
          <el-select v-model="selectedServer.id" placeholder="请选择服务器" @change="handleServerChange" style="width: 100%">
            <el-option label="默认(localhost)" value="" />
            <el-option
              v-for="item in serverList"
              :key="item.serverId"
              :label="item.serverName"
              :value="item.serverId"
            >
              <span>{{ item.serverName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.serverIp }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据库类型" prop="dbType">
          <el-select v-model="form.dbType" placeholder="请选择数据库类型" @change="handleDbTypeChange">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="连接地址" prop="dbUrl">
          <el-input v-model="form.dbUrl" placeholder="请输入连接地址，如jdbc:mysql://localhost:3306/dbname" />
          <span class="el-form-item__description" v-if="form.dbType === 'MySQL'">MySQL格式: jdbc:mysql://localhost:3306/dbname</span>
          <span class="el-form-item__description" v-else-if="form.dbType === 'Oracle'">Oracle格式: jdbc:oracle:thin:@localhost:1521:orcl</span>
          <span class="el-form-item__description" v-else-if="form.dbType === 'SQLServer'">SQLServer格式: jdbc:sqlserver://localhost:1433;databaseName=dbname</span>
          <span class="el-form-item__description" v-else-if="form.dbType === 'PostgreSQL'">PostgreSQL格式: jdbc:postgresql://localhost:5432/dbname</span>
        </el-form-item>
        <el-form-item label="驱动类" prop="dbDriver">
          <el-input v-model="form.dbDriver" placeholder="请输入驱动类，会根据数据库类型自动填充" />
          <span class="el-form-item__description" v-if="form.dbType === 'MySQL'">MySQL驱动: com.mysql.cj.jdbc.Driver</span>
          <span class="el-form-item__description" v-else-if="form.dbType === 'Oracle'">Oracle驱动: oracle.jdbc.OracleDriver</span>
          <span class="el-form-item__description" v-else-if="form.dbType === 'SQLServer'">SQLServer驱动: com.microsoft.sqlserver.jdbc.SQLServerDriver</span>
          <span class="el-form-item__description" v-else-if="form.dbType === 'PostgreSQL'">PostgreSQL驱动: org.postgresql.Driver</span>
        </el-form-item>
        <el-form-item label="用户名" prop="dbUsername">
          <el-input v-model="form.dbUsername" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="dbPassword">
          <el-input v-model="form.dbPassword" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDbConfig, getDbConfig, delDbConfig, addDbConfig, updateDbConfig, testDbConnection } from "@/api/system/dbconfig";
import { listServers } from "@/api/system/dbconfig";

export default {
  name: "DbConfig",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据库配置表格数据
      dbConfigList: [],
      // 服务器列表
      serverList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 数据库类型数据字典
      typeOptions: [
        {
          dictValue: "MySQL",
          dictLabel: "MySQL"
        },
        {
          dictValue: "Oracle",
          dictLabel: "Oracle"
        },
        {
          dictValue: "SQLServer",
          dictLabel: "SQLServer"
        },
        {
          dictValue: "PostgreSQL",
          dictLabel: "PostgreSQL"
        }
      ],
      // 状态数据字典
      statusOptions: [
        {
          dictValue: "0",
          dictLabel: "正常"
        },
        {
          dictValue: "1",
          dictLabel: "停用"
        }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dbName: undefined,
        dbType: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 选择的服务器信息
      selectedServer: {
        id: undefined,
        ip: "localhost",
        port: ""
      },
      // 表单校验
      rules: {
        dbName: [
          { required: true, message: "数据库名称不能为空", trigger: "blur" },
          { min: 2, max: 100, message: '数据库名称长度必须在2到100个字符之间', trigger: 'blur' }
        ],
        dbType: [
          { required: true, message: "数据库类型不能为空", trigger: "change" }
        ],
        dbUrl: [
          { required: true, message: "连接地址不能为空", trigger: "blur" }
        ],
        dbDriver: [
          { required: true, message: "驱动类不能为空", trigger: "blur" }
        ],
        dbUsername: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        dbPassword: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getServerList();
  },
  methods: {
    /** 查询数据库配置列表 */
    getList() {
      this.loading = true;
      listDbConfig(this.queryParams).then(response => {
        this.dbConfigList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询服务器列表 */
    getServerList() {
      listServers().then(response => {
        this.serverList = response.rows || [];
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        dbId: undefined,
        dbName: undefined,
        dbType: 'MySQL',
        dbUrl: undefined,
        dbDriver: 'com.mysql.cj.jdbc.Driver',
        dbUsername: undefined,
        dbPassword: undefined,
        status: "0",
        remark: undefined
      };
      this.selectedServer = {
        id: undefined,
        ip: 'localhost',
        port: '3306'
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dbId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据库配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const dbId = row.dbId || this.ids[0];
      getDbConfig(dbId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改数据库配置";
      });
    },
    /** 测试连接按钮操作 */
    handleTest(row) {
      const dbConfig = row;
      this.$modal.confirm('是否确认测试数据库连接?').then(function() {
        return testDbConnection(dbConfig);
      }).then(response => {
        this.$modal.msgSuccess(response.msg);
      }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.dbId != undefined) {
            updateDbConfig(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDbConfig(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dbIds = row.dbId || this.ids;
      this.$modal.confirm('是否确认删除数据库配置编号为"' + dbIds + '"的数据项?').then(function() {
        return delDbConfig(dbIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/dbconfig/export', {
        ...this.queryParams
      }, `dbconfig_${new Date().getTime()}.xlsx`);
    },
    /** 数据库类型变更处理 */
    handleDbTypeChange(value) {
      // 根据数据库类型设置默认驱动类
      switch (value) {
        case 'MySQL':
          this.form.dbDriver = 'com.mysql.cj.jdbc.Driver';
          break;
        case 'Oracle':
          this.form.dbDriver = 'oracle.jdbc.OracleDriver';
          break;
        case 'SQLServer':
          this.form.dbDriver = 'com.microsoft.sqlserver.jdbc.SQLServerDriver';
          break;
        case 'PostgreSQL':
          this.form.dbDriver = 'org.postgresql.Driver';
          break;
      }
      
      // 更新默认端口
      this.selectedServer.port = this.getDefaultPortByDbType(value);
      
      // 更新连接地址
      this.updateConnectionUrl();
    },
    /** 数据库名称变更处理 */
    handleDbNameChange() {
      // 更新连接地址
      this.updateConnectionUrl();
    },
    /** 服务器变更处理 */
    handleServerChange(serverId) {
      // 根据服务器ID获取服务器信息
      if (serverId === '' || serverId === undefined) {
        this.selectedServer.ip = 'localhost';
        this.selectedServer.port = '';
      } else {
        const server = this.serverList.find(item => item.serverId === serverId);
        if (server) {
          this.selectedServer.ip = server.serverIp;
          this.selectedServer.port = server.serverPort.toString();
        }
      }
      // 更新连接地址
      this.updateConnectionUrl();
    },
    
    /** 获取数据库类型默认端口 */
    getDefaultPortByDbType(dbType) {
      switch (dbType) {
        case 'MySQL':
          return '3306';
        case 'Oracle':
          return '1521';
        case 'SQLServer':
          return '1433';
        case 'PostgreSQL':
          return '5432';
        default:
          return '';
      }
    },
    
    /** 更新连接地址 */
    updateConnectionUrl() {
      if (!this.form.dbType) return;
      
      const ip = this.selectedServer.ip || 'localhost';
      const port = this.selectedServer.port || this.getDefaultPortByDbType(this.form.dbType);
      const dbName = this.form.dbName || 'dbname';
      
      switch (this.form.dbType) {
        case 'MySQL':
          this.form.dbUrl = `jdbc:mysql://${ip}:${port}/${dbName}`;
          break;
        case 'Oracle':
          this.form.dbUrl = `jdbc:oracle:thin:@${ip}:${port}:orcl`;
          break;
        case 'SQLServer':
          this.form.dbUrl = `jdbc:sqlserver://${ip}:${port};databaseName=${dbName}`;
          break;
        case 'PostgreSQL':
          this.form.dbUrl = `jdbc:postgresql://${ip}:${port}/${dbName}`;
          break;
      }
    }
  }
};
</script>

<style scoped>
.el-form-item__description {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  padding-top: 4px;
  display: block;
}
</style> 